#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
桌面助手打包脚本
使用 PyInstaller 将桌面管理器打包成 exe 文件
"""

import os
import subprocess
import sys
from pathlib import Path

def create_icon():
    """创建简单的ICO图标文件"""
    # 这里可以添加图标创建逻辑，暂时跳过
    pass

def build_exe():
    """打包成exe文件"""
    print("🔨 开始打包桌面助手...")
    
    # 当前目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # PyInstaller 命令参数
    cmd = [
        'pyinstaller',
        '--onefile',                    # 打包成单个文件
        '--windowed',                   # 无控制台窗口
        '--name=桌面助手',               # 可执行文件名称
        '--distpath=dist',              # 输出目录
        '--workpath=build',             # 临时目录
        '--specpath=.',                 # spec文件目录
        '--clean',                      # 清理临时文件
        '--noconfirm',                  # 不询问覆盖
        # '--add-data=config.json;.',     # 包含配置文件
        '--hidden-import=config',       # 包含config模块
        '--hidden-import=tkinter',      # 明确包含tkinter
        '--hidden-import=tkinter.ttk',  # 包含ttk
        '--optimize=2',                 # 代码优化
        'desktop_manager.py'            # 主程序文件
    ]
    
    print(f"💻 执行命令: {' '.join(cmd)}")
    
    try:
        # 执行打包命令
        result = subprocess.run(cmd, cwd=current_dir, capture_output=True, text=True, encoding='utf-8')
        
        if result.returncode == 0:
            print("✅ 打包成功！")
            print(f"📁 输出文件: {os.path.join(current_dir, 'dist', '桌面助手.exe')}")
            
            # 检查文件是否存在
            exe_path = os.path.join(current_dir, 'dist', '桌面助手.exe')
            if os.path.exists(exe_path):
                file_size = os.path.getsize(exe_path) / (1024 * 1024)  # MB
                print(f"📏 文件大小: {file_size:.2f} MB")
            
            print("\n🎉 打包完成！可执行文件位于 dist 目录中")
            print("📋 注意事项:")
            print("   1. 首次运行时会自动创建配置文件")
            print("   2. 确保运行环境有写入权限")
            print("   3. 可以将exe文件复制到任意位置运行")
            
        else:
            print("❌ 打包失败！")
            print("错误输出:")
            print(result.stderr)
            
    except Exception as e:
        print(f"❌ 打包过程中出现错误: {str(e)}")

def create_advanced_spec():
    """创建高级spec文件用于更复杂的打包配置"""
    spec_content = '''# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(
    ['desktop_manager.py'],
    pathex=[],
    binaries=[],
    datas=[
        ('config.py', '.'),
    ],
    hiddenimports=[
        'config',
        'tkinter',
        'tkinter.ttk',
        'threading',
        'json',
        'shutil',
        'datetime',
        'pathlib'
    ],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='桌面助手',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    version='version_info.txt',
    uac_admin=False,
    icon='icon.ico'
)
'''
    
    with open('desktop_manager.spec', 'w', encoding='utf-8') as f:
        f.write(spec_content)
    
    print("📄 已创建高级配置文件: desktop_manager.spec")

def create_version_info():
    """创建版本信息文件"""
    version_info = '''# UTF-8
#
# For more details about fixed file info 'ffi' see:
# http://msdn.microsoft.com/en-us/library/ms646997.aspx
VSVersionInfo(
  ffi=FixedFileInfo(
    filevers=(1,0,0,0),
    prodvers=(1,0,0,0),
    mask=0x3f,
    flags=0x0,
    OS=0x4,
    fileType=0x1,
    subtype=0x0,
    date=(0, 0)
    ),
  kids=[
    StringFileInfo(
      [
      StringTable(
        u'080404B0',
        [StringStruct(u'CompanyName', u'桌面助手'),
        StringStruct(u'FileDescription', u'智能桌面文件整理工具'),
        StringStruct(u'FileVersion', u'1.0.0.0'),
        StringStruct(u'InternalName', u'desktop_manager'),
        StringStruct(u'LegalCopyright', u'Copyright © 2024'),
        StringStruct(u'OriginalFilename', u'桌面助手.exe'),
        StringStruct(u'ProductName', u'桌面助手'),
        StringStruct(u'ProductVersion', u'1.0.0.0')])
      ]), 
    VarFileInfo([VarStruct(u'Translation', [2052, 1200])])
  ]
)
'''
    
    with open('version_info.txt', 'w', encoding='utf-8') as f:
        f.write(version_info)
    
    print("📋 已创建版本信息文件: version_info.txt")

def main():
    """主函数"""
    print("=" * 50)
    print("🖥️  桌面助手 - EXE 打包工具")
    print("=" * 50)
    
    # 检查必要文件
    required_files = ['desktop_manager.py', 'config.py']
    missing_files = []
    
    for file in required_files:
        if not os.path.exists(file):
            missing_files.append(file)
    
    if missing_files:
        print(f"❌ 缺少必要文件: {', '.join(missing_files)}")
        return
    
    print("✅ 文件检查通过")
    
    # 创建版本信息文件
    create_version_info()
    
    # 执行打包
    build_exe()
    
    print("\n" + "=" * 50)
    print("🎯 打包任务完成")
    print("=" * 50)

if __name__ == "__main__":
    main() 